package com.mj.util;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

/**
 * spring的El表达式
 * 
 * @author majie
 *
 */
@Component
public class SplParse {

	private static ExpressionParser parse = new SpelExpressionParser();

	// 通过el表达式来获取函数的入参
	public static String getKey(String key, String[] paramsName, Object[] args) {
		Expression exp = parse.parseExpression(key);
		StandardEvaluationContext context = new StandardEvaluationContext();
		if (args.length <= 0) {
			return null;
		}
		for (int i = 0; i < args.length; i++) {
			context.setVariable(paramsName[i], args[i]);
		}
		return exp.getValue(context, String.class);
	}

	// 通过el表达式来获取函数的入参
	public static String getKey(String key,ProceedingJoinPoint pjp){
		Object[] args = pjp.getArgs();
		MethodSignature ms = (MethodSignature)pjp.getSignature();
		Method method = ms.getMethod();
		String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(method);
		return SplParse.getKey(key, parameterNames, args);
	}

	public static void main(String[] args) {
		String key = "#user.id + '||' +#userCode";
		// args赋值
		Object[] _args = new Object[2];
		User user = new User();
		user.setId("123");
		_args[0] = user;
		_args[1] = "zhangsan";

		// paramName赋值
		String[] paramsName = new String[] { "user", "userCode" };
		System.out.println(SplParse.getKey(key, paramsName, _args));

	}
	
}

//用作测试的类
class User{
	private String id;
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
